<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getProjectTop10Service } from '@/api/report'

const props = defineProps({
  dateRange: {
    type: Object,
    required: true
  }
})

const chart = ref(null) // 获取DOM引用
let myChart = null // 持久化图表实例
const projectNameList = ref() // 服务项目名称列表
const otherData = ref() // 其他数据

const getProjectTop10 = async () => {
  const res = await getProjectTop10Service(props.dateRange)
  // 横向BarChart需要按salesCount升序，才能将排名靠前的放上面
  const sortedData = res.data.data.sort((a, b) => a.salesCount - b.salesCount)
  // 提取数据
  projectNameList.value = sortedData.map((item) => item.projectName)
  otherData.value = sortedData.map((item) => ({
    value: item.salesCount,
    projectName: item.projectName,
    projectPrice: item.projectPrice,
    projectRating: item.projectRating
  }))
  updateChart()
}

// 初始化图表基础配置
const initChart = () => {
  myChart = echarts.init(chart.value)
  const baseOption = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const dataItem = params[0]
        return (
          `${dataItem.data.projectName}<br/>` +
          `${dataItem.marker}销量：<b>${dataItem.data.value}</b><br/>` +
          `${dataItem.marker}价格：<b>¥${(dataItem.data.projectPrice / 100).toFixed(2)}</b><br/>` +
          `${dataItem.marker}评分：<b>${
            dataItem.data.projectRating !== null ? dataItem.data.projectRating + '分' : '暂无'
          }</b>`
        )
      }
    },
    grid: {
      left: '1%',
      right: '1%',
      bottom: '3%',
      top: '4%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      minInterval: 1 // 最小间隔为1
    },
    yAxis: {
      type: 'category'
    },
    series: [
      {
        name: '销量',
        type: 'bar'
      }
    ]
  }
  myChart.setOption(baseOption)
}

// 更新图表数据
const updateChart = () => {
  const option = {
    yAxis: {
      data: projectNameList.value
    },
    series: [
      {
        data: otherData.value
      }
    ]
  }
  myChart.setOption(option)
}

onMounted(() => {
  initChart()
})

watch(() => props.dateRange, getProjectTop10, { immediate: true })
</script>

<template>
  <div ref="chart" style="width: 100%; height: 350px"></div>
</template>
